package com.ciwong.mobilelib.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;

import com.ciwong.libs.utils.CWLog;

/**
 * Created by res-mingyang on 2015/8/25.
 */
public class ImageViewColorFilter extends ImageView
{
    private boolean isClick;

    public ImageViewColorFilter(Context context)
    {
        super(context);
    }

    public ImageViewColorFilter(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public ImageViewColorFilter(Context context, AttributeSet attrs,
            int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        try {
            super.onDraw(canvas);
        } catch (Exception e) {
           CWLog.d("debug","MyImageView  -> onDraw() Canvas: trying to use a recycled bitmap");
        }

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event)
    {
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                isClick = true;
                setColorFilter(Color.parseColor("#33333333"));
                break;
            case MotionEvent.ACTION_MOVE:
                isOutSide(event);
                break;
            case MotionEvent.ACTION_UP:
                if (isClick)
                {
                    setColorFilter(Color.TRANSPARENT);
                    performClick();
                }
                break;
        }
        return true;
    }

    private void isOutSide(MotionEvent event)
    {
        float viewX = event.getX();
        float viewY = event.getY();
        if (viewX < 0 || viewY < 0 || viewX > getWidth() || viewY > getHeight())
        {
            isClick = false;
            setColorFilter(Color.TRANSPARENT);
        }
        else if (viewX > 0 || viewY > 0 || viewX < getWidth()
                || viewY < getHeight())
        {
            isClick = true;
            setColorFilter(Color.parseColor("#33333333"));
        }
    }
}
